package com.ruoyi.common.opio.util;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.magus.OPException;
import com.magus.jdbc.OPResultSet;
import com.magus.opio.net.IOPConnect;
import lombok.extern.slf4j.Slf4j;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ExampleBase {

	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

	public static Map<String,Object> toResult() {
		Map<String, Object> result = new HashMap<>();
		IOPConnect conn = null;
		OPResultSet rs = null;
		try {
			conn = OPPool.getConn();
			if (conn == null) {
				return result;
			}
			String sql = "select PN,AV from REALTIME";
			rs = conn.execSQL(sql);
			ResultSetMetaData rsmd = rs.getMetaData();
			String formatStr = "%-20s";
			while (rs.next()) {
				Map<String, Object> data = new HashMap<>();
				for (int i = 1; i <= rsmd.getColumnCount(); i++) {
					String key = String.format(formatStr, rsmd.getColumnLabel(i).toUpperCase()).trim();
					if (rsmd.getColumnType(i) == Types.TIMESTAMP) {
						data.put(key,sdf.format(rs.getDate(i)));
					} else if (rsmd.getColumnType(i) == Types.BOOLEAN) {
						data.put(key,rs.getBoolean(i));
					} else if (rsmd.getColumnType(i) == Types.DOUBLE) {
						data.put(key,rs.getBytes(i));
					} else {
						data.put(key,String.format(formatStr, rs.getString(i)).trim());
					}
				}
				String pn = data.get("PN").toString();
				String av = data.get("AV").toString();
				if (StrUtil.isNotEmpty(av)) {
					String[] split = av.split("\\.");
					if (split.length > 1) {
						av = split[0] + "." + StrUtil.sub(split[1],0,3);
					}
				}
				result.put(pn,av);
			}
		} catch (OPException | SQLException e) {
			log.error("获取实时数据库数据失败: {}",e.getMessage());
		} finally {
			OPPool.close(conn,rs);
		}
		return result;
	}






















}
